'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import CarCard from '@/components/CarCard';

interface Brand {
  brand: string;
  name: string;
  alphabet: string;
  country: string;
  hot: string;
  desc: string;
  story: string;
}

import { Car } from '@/data/cars';

export default function BrandDetailPage() {
  const params = useParams();
  const slug = params.slug as string;
  
  const [brand, setBrand] = useState<Brand | null>(null);
  const [recommendedCars, setRecommendedCars] = useState<Car[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('overview');

  useEffect(() => {
    const loadData = async () => {
      try {
        // 加载品牌数据
        const brandData = await import('@/../public/brandData.js');
        const foundBrand = brandData.default.find(b => b.brand === slug);
        setBrand(foundBrand || null);

        // 模拟推荐车辆数据
        const mockCars: Car[] = Array.from({ length: 6 }, (_, i) => ({
          id: `recommend-${i + 1}`,
          name: `${foundBrand?.name || '品牌'} 车型 ${i + 1}`,
          brand: foundBrand?.name || '',
          model: `MODEL-${i + 1}`,
          type: Math.random() > 0.5 ? 'new' : 'used' as 'new' | 'used',
          fuelType: ['electric', 'hybrid', 'gasoline', 'diesel'][Math.floor(Math.random() * 4)] as 'gasoline' | 'diesel' | 'electric' | 'hybrid',
          price: 150000 + Math.random() * 500000,
          year: 2023 + Math.floor(Math.random() * 2),
          images: ['/cars/default-car.jpg'],
          description: `${foundBrand?.name} 车型，性能卓越，配置丰富，${Math.random() > 0.5 ? '新车' : '精品二手车'}`,
          features: ['空调', '导航', '倒车影像', '蓝牙', '天窗', '真皮座椅'],
          specifications: {
            engine: `${1.5 + Math.random() * 2.5}L ${Math.random() > 0.5 ? '涡轮增压' : '自然吸气'}`,
            transmission: Math.random() > 0.5 ? 'automatic' : 'manual' as 'automatic' | 'manual',
            drivetrain: ['前驱', '后驱', '四驱'][Math.floor(Math.random() * 3)],
            fuelEconomy: `${5 + Math.random() * 10}L/100km`,
            seating: 5
          },
          mileage: Math.random() > 0.5 ? 10000 + Math.random() * 50000 : undefined,
          color: ['白色', '黑色', '银色', '蓝色', '红色', '灰色'][Math.floor(Math.random() * 6)],
          location: ['北京', '上海', '广州', '深圳', '杭州', '成都'][Math.floor(Math.random() * 6)],
          status: 'available' as 'available' | 'sold' | 'reserved',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        }));
        setRecommendedCars(mockCars);
      } catch (error) {
        console.error('加载数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [slug]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="container mx-auto px-4">
          <div className="text-center">
            <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">加载品牌详情中...</p>
          </div>
        </div>
      </div>
    );
  }

  if (!brand) {
    return (
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="container mx-auto px-4 text-center">
          <div className="text-6xl mb-4">😕</div>
          <h1 className="text-3xl font-bold text-gray-900 mb-4">品牌未找到</h1>
          <p className="text-gray-600 mb-8">抱歉，找不到您要查看的品牌</p>
          <Link href="/brands" className="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition-colors">
            返回品牌列表
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4">
        {/* Breadcrumb */}
        <nav className="flex items-center space-x-2 text-sm text-gray-600 mb-6">
          <Link href="/" className="hover:text-blue-600">首页</Link>
          <span>›</span>
          <Link href="/brands" className="hover:text-blue-600">品牌</Link>
          <span>›</span>
          <span className="text-gray-900">{brand.name}</span>
        </nav>

        {/* Brand Header */}
        <div className="bg-white rounded-2xl shadow-lg overflow-hidden mb-8">
          <div className="p-8">
            <div className="flex flex-col md:flex-row items-center md:items-start space-y-6 md:space-y-0 md:space-x-8">
              {/* Brand Logo */}
              <div className="flex-shrink-0">
                <div className="w-32 h-32 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white text-4xl font-bold shadow-2xl">
                  {brand.alphabet}
                </div>
              </div>

              {/* Brand Info */}
              <div className="flex-1 text-center md:text-left">
                <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-4">
                  <div>
                    <h1 className="text-4xl font-bold text-gray-900 mb-2">{brand.name}</h1>
                    <div className="flex items-center justify-center md:justify-start space-x-4 text-gray-600">
                      <span className="flex items-center">
                        <svg className="w-5 h-5 mr-1" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M10 2a8 8 0 100 16 8 8 0 000-16zM4 10a6 6 0 1112 0 6 6 0 01-12 0z" clipRule="evenodd"/>
                          <path d="M10 12a2 2 0 100-4 2 2 0 000 4z"/>
                        </svg>
                        {brand.country}
                      </span>
                      <span>•</span>
                      <span>{brand.brand}</span>
                      {brand.hot === '1' && (
                        <>
                          <span>•</span>
                          <span className="bg-red-100 text-red-800 px-2 py-1 rounded-full text-sm font-semibold">热门品牌</span>
                        </>
                      )}
                    </div>
                  </div>
                </div>

                <p className="text-lg text-gray-700 leading-relaxed mb-6">{brand.desc}</p>

                {/* Quick Stats */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                  <div className="text-center p-3 bg-blue-50 rounded-lg">
                    <div className="text-2xl font-bold text-blue-600">8+</div>
                    <div className="text-sm text-gray-600">车型数量</div>
                  </div>
                  <div className="text-center p-3 bg-green-50 rounded-lg">
                    <div className="text-2xl font-bold text-green-600">20-100万</div>
                    <div className="text-sm text-gray-600">价格区间</div>
                  </div>
                  <div className="text-center p-3 bg-purple-50 rounded-lg">
                    <div className="text-2xl font-bold text-purple-600">4.8</div>
                    <div className="text-sm text-gray-600">用户评分</div>
                  </div>
                  <div className="text-center p-3 bg-orange-50 rounded-lg">
                    <div className="text-2xl font-bold text-orange-600">95%</div>
                    <div className="text-sm text-gray-600">满意度</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div className="bg-white rounded-lg shadow-md mb-8">
          <div className="border-b border-gray-200">
            <nav className="flex space-x-8 px-6">
              {['overview', 'story', 'models', 'reviews'].map(tab => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={`py-4 px-1 border-b-2 font-medium text-sm ${
                    activeTab === tab
                      ? 'border-blue-500 text-blue-600'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                  }`}
                >
                  {tab === 'overview' && '品牌概览'}
                  {tab === 'story' && '品牌故事'}
                  {tab === 'models' && '车型展示'}
                  {tab === 'reviews' && '用户评价'}
                </button>
              ))}
            </nav>
          </div>

          {/* Tab Content */}
          <div className="p-6">
            {activeTab === 'overview' && (
              <div className="prose max-w-none">
                <h3 className="text-xl font-semibold mb-4">品牌简介</h3>
                <p className="text-gray-700 leading-relaxed mb-6">{brand.desc}</p>
                
                <div className="grid md:grid-cols-2 gap-6">
                  <div>
                    <h4 className="font-semibold mb-2">品牌特色</h4>
                    <ul className="space-y-2 text-gray-600">
                      <li>• 创新技术研发</li>
                      <li>• 卓越品质控制</li>
                      <li>• 环保可持续发展</li>
                      <li>• 智能化驾驶体验</li>
                    </ul>
                  </div>
                  <div>
                    <h4 className="font-semibold mb-2">市场表现</h4>
                    <ul className="space-y-2 text-gray-600">
                      <li>• 全球销量领先</li>
                      <li>• 用户满意度高</li>
                      <li>• 技术创新奖获得者</li>
                      <li>• 环保认证企业</li>
                    </ul>
                  </div>
                </div>
              </div>
            )}

            {activeTab === 'story' && (
              <div className="prose max-w-none">
                <h3 className="text-xl font-semibold mb-4">品牌故事</h3>
                <div className="bg-gray-50 rounded-lg p-6 mb-6">
                  <p className="text-gray-700 leading-relaxed whitespace-pre-line">{brand.story}</p>
                </div>
                
                <div className="grid md:grid-cols-3 gap-4 text-center">
                  <div className="p-4 bg-blue-50 rounded-lg">
                    <div className="text-2xl font-bold text-blue-600 mb-1">
                      {brand.story.match(/\d{4}/)?.[0] || '2000'}
                    </div>
                    <div className="text-sm text-gray-600">创立年份</div>
                  </div>
                  <div className="p-4 bg-green-50 rounded-lg">
                    <div className="text-2xl font-bold text-green-600 mb-1">
                      {2024 - parseInt(brand.story.match(/\d{4}/)?.[0] || '2000')}+
                    </div>
                    <div className="text-sm text-gray-600">发展历程</div>
                  </div>
                  <div className="p-4 bg-purple-50 rounded-lg">
                    <div className="text-2xl font-bold text-purple-600 mb-1">全球</div>
                    <div className="text-sm text-gray-600">市场覆盖</div>
                  </div>
                </div>
              </div>
            )}

            {activeTab === 'models' && (
              <div>
                <h3 className="text-xl font-semibold mb-6">推荐车型</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {recommendedCars.map(car => (
                    <CarCard key={car.id} car={car} />
                  ))}
                </div>
                <div className="text-center mt-8">
                  <Link 
                    href="/cars" 
                    className="bg-blue-600 text-white px-8 py-3 rounded-lg hover:bg-blue-700 transition-colors inline-block"
                  >
                    查看全部车型
                  </Link>
                </div>
              </div>
            )}

            {activeTab === 'reviews' && (
              <div>
                <h3 className="text-xl font-semibold mb-6">用户评价</h3>
                <div className="space-y-6">
                  {[1, 2, 3].map(i => (
                    <div key={i} className="border border-gray-200 rounded-lg p-6">
                      <div className="flex items-center mb-4">
                        <div className="w-10 h-10 bg-gray-300 rounded-full mr-4"></div>
                        <div>
                          <div className="font-semibold">用户 {i}</div>
                          <div className="flex text-yellow-400">
                            {'★'.repeat(5)}
                          </div>
                        </div>
                      </div>
                      <p className="text-gray-700">"{brand.name}的车辆质量非常可靠，售后服务也很到位，非常满意！"</p>
                      <div className="text-sm text-gray-500 mt-2">2024年购买 · {['豪华版', '标准版', '运动版'][i-1]}</div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Related Brands */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-xl font-semibold mb-4">相关品牌</h3>
          <div className="flex space-x-4 overflow-x-auto pb-2">
            {['byd', 'tesla', 'xiaomi', 'nio'].map(relatedBrand => (
              <Link 
                key={relatedBrand} 
                href={`/brands/${relatedBrand}`}
                className="flex-shrink-0 bg-gray-50 hover:bg-gray-100 rounded-lg px-4 py-2 transition-colors"
              >
                {relatedBrand.toUpperCase()}
              </Link>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}